package cn.ocars.playgame.pencilstudy.ui.components

import android.view.MotionEvent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathMeasure
import kotlin.math.min
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.ocars.playgame.pencilstudy.ui.theme.BackgroundWhite
import cn.ocars.playgame.pencilstudy.ui.theme.ButtonBlue
import cn.ocars.playgame.pencilstudy.ui.theme.ButtonGreen
import cn.ocars.playgame.pencilstudy.ui.theme.ButtonRed
import cn.ocars.playgame.pencilstudy.ui.theme.PrimaryBlue
import cn.ocars.playgame.pencilstudy.ui.theme.TextPrimary
import cn.ocars.playgame.pencilstudy.ui.theme.TextWhite

data class WritingCardData(
    val id: String,
    val title: String,
    val targetCharacter: String,
    val characterType: CharacterType,
    val difficulty: Int = 1
)

// CharacterType 枚举已移动到 WritingCharacterData.kt

@Composable
fun MiniWritingCard(
    character: String,
    onWritingComplete: (Float) -> Unit,
    modifier: Modifier = Modifier
) {
    var path by remember { mutableStateOf(Path()) }
    var isWriting by remember { mutableStateOf(false) }
    var score by remember { mutableStateOf(0f) }
    var showResult by remember { mutableStateOf(false) }
    var currentPressure by remember { mutableStateOf(0f) }
    var strokeCount by remember { mutableStateOf(0) } // 记录笔画数量
    var hasCompletedStrokes by remember { mutableStateOf(false) } // 标记是否完成所有笔画
    var currentPath by remember { mutableStateOf(Path()) } // 当前笔画路径
    var allPaths by remember { mutableStateOf<List<Path>>(emptyList()) } // 所有已完成笔画的路径
    var forceRedraw by remember { mutableStateOf(0) } // 强制重绘计数器
    
    // 预计算压力值获取逻辑，避免每次触摸事件都进行版本检查
    val canGetPressure = remember { android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q }
    
    // 优化：预计算画笔属性，避免每次绘制时重新创建
    val strokeStyle = remember {
        Stroke(
            width = 4f,
            cap = StrokeCap.Round,
            join = StrokeJoin.Round
        )
    }
    
    // 优化：使用更高效的状态更新机制
    val updatePath = remember<(Offset) -> Unit> {
        { offset ->
            currentPath.lineTo(offset.x, offset.y)
            forceRedraw++
        }
    }
    
    // 优化：离屏渲染缓存 - 存储已完成的笔画位图
    var cachedBitmap by remember { mutableStateOf<android.graphics.Bitmap?>(null) }
    var cacheDirty by remember { mutableStateOf(true) } // 标记缓存是否需要更新
    
    // 优化：路径点集合，用于平滑处理
    var currentPoints by remember { mutableStateOf<List<Offset>>(emptyList()) }
    
    // 优化：平滑处理路径点的函数
    val smoothPath = remember<(List<Offset>) -> Path> {
        { points ->
            if (points.isEmpty()) return@remember Path()
            if (points.size == 1) return@remember Path().apply { moveTo(points[0].x, points[0].y) }
            
            val path = Path()
            path.moveTo(points[0].x, points[0].y)
            
            // 使用二次贝塞尔曲线平滑路径
            for (i in 1 until points.size) {
                val cx = (points[i].x + points[i - 1].x) / 2
                val cy = (points[i].y + points[i - 1].y) / 2
                path.quadraticBezierTo(points[i - 1].x, points[i - 1].y, cx, cy)
            }
            
            path
        }
    }
    
    // 根据字符类型预估笔画数
    val estimatedStrokes = when {
        character.length == 1 && character.first() in '0'..'9' -> 1 // 数字通常1笔
        character.length == 1 && character.first() in 'A'..'Z' -> 3 // 大写字母通常3笔
        character.length == 1 && character.first() in 'a'..'z' -> 2 // 小写字母通常2笔
        character == "一" -> 1
        character == "人" -> 2
        character == "大" -> 3
        character == "小" -> 3
        else -> 2 // 默认2笔
    }
    
    Surface(
        modifier = modifier
            .size(150.dp)
            .border(2.dp, PrimaryBlue, RoundedCornerShape(12.dp)),
        shape = RoundedCornerShape(12.dp),
        color = BackgroundWhite,
        shadowElevation = 8.dp
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(8.dp)
        ) {
            // 书写区域
        Canvas(
            modifier = Modifier
                .fillMaxSize()
                .pointerInput(Unit) {
                    detectDragGestures(
                        onDragStart = { offset ->
                            // 优化：立即创建路径并移动到起始点，减少延迟
                            isWriting = true
                            currentPath = Path()
                            currentPath.moveTo(offset.x, offset.y)
                            currentPoints = listOf(offset) // 初始化路径点
                            forceRedraw++ // 立即触发重绘，确保起始点显示
                        },
                        onDragEnd = {
                            isWriting = false
                            // 保存当前笔画
                            allPaths = allPaths + currentPath
                            strokeCount++ // 增加笔画计数
                            currentPoints = emptyList() // 清空当前路径点
                            cacheDirty = true // 标记缓存需要更新
                            
                            // 检查是否完成所有笔画
                            if (allPaths.size >= estimatedStrokes) {
                                hasCompletedStrokes = true
                                // 简单的评分逻辑，基于压力值
                                score = if (currentPressure > 0) {
                                    // 压感评分：压力越稳定，分数越高
                                    val pressureScore = (1 - Math.abs(currentPressure - 0.5f)) * 50
                                    pressureScore + 50 // 50-100之间的分数
                                } else {
                                    (Math.random() * 40 + 60).toFloat() // 60-100之间的随机分数
                                }
                                showResult = true
                                onWritingComplete(score)
                            }
                            
                            // 重置当前路径
                            currentPath = Path()
                            forceRedraw++ // 触发重绘
                        },
                        onDragCancel = {
                            isWriting = false
                            // 取消当前笔画，不保存
                            currentPath = Path()
                            currentPoints = emptyList() // 清空当前路径点
                            forceRedraw++ // 触发重绘
                        },
                        onDrag = { change, dragAmount ->
                            // 优化：直接更新路径，减少条件判断
                            // 使用预计算的updatePath函数，减少函数调用开销
                            updatePath(change.position)
                            currentPoints = currentPoints + change.position // 添加新点到路径点集合
                            
                            // 优化：简化压力值获取逻辑，减少计算开销
                            currentPressure = if (canGetPressure) {
                                0.5f // 使用默认值，避免复杂的压力值获取逻辑
                            } else {
                                0f
                            }
                            
                            // 强制触发重绘
                            change.consume()
                        }
                    )
                }
        ) {
            // 绘制背景
            drawRect(Color.White, size = size)
            
            // 绘制网格线（可选）
            drawLine(
                color = Color.LightGray,
                start = Offset(0f, size.height / 2),
                end = Offset(size.width, size.height / 2),
                strokeWidth = 1f
            )
            drawLine(
                color = Color.LightGray,
                start = Offset(size.width / 2, 0f),
                end = Offset(size.width / 2, size.height),
                strokeWidth = 1f
            )
            
            // 优化：创建或更新离屏渲染缓存
            if (cacheDirty && allPaths.isNotEmpty()) {
                // 创建新的位图用于缓存
                val newBitmap = android.graphics.Bitmap.createBitmap(
                    size.width.toInt(),
                    size.height.toInt(),
                    android.graphics.Bitmap.Config.ARGB_8888
                )
                
                // 使用Android原生Canvas绘制到离屏位图
                val androidCanvas = android.graphics.Canvas(newBitmap)
                val paint = android.graphics.Paint().apply {
                    color = android.graphics.Color.BLACK
                    style = android.graphics.Paint.Style.STROKE
                    strokeWidth = 4f
                    isAntiAlias = true
                    strokeCap = android.graphics.Paint.Cap.ROUND
                    strokeJoin = android.graphics.Paint.Join.ROUND
                }
                
                // 绘制所有已完成的路径到离屏位图
                allPaths.forEach { path ->
                    // 使用路径点集合重建路径
                    val androidPath = android.graphics.Path()
                    val pathMeasure = PathMeasure()
                    pathMeasure.setPath(path, false)
                    val pathLength = pathMeasure.length
                    
                    if (pathLength > 0) {
                        // 获取路径起点
                        val startPoint = pathMeasure.getPosition(0f)
                        androidPath.moveTo(startPoint.x, startPoint.y)
                        
                        // 使用路径采样点来重建路径
                        val sampleCount = min(100, pathLength.toInt()) // 采样点数量
                        for (i in 1..sampleCount) {
                            val distance = (pathLength * i) / sampleCount
                            val point = pathMeasure.getPosition(distance)
                            androidPath.lineTo(point.x, point.y)
                        }
                    }
                    
                    androidCanvas.drawPath(androidPath, paint)
                }
                
                cachedBitmap = newBitmap
                cacheDirty = false
            }
            
            // 优化：绘制离屏缓存位图（如果存在）
            cachedBitmap?.let { bitmap ->
                drawImage(
                    image = bitmap.asImageBitmap(),
                    topLeft = Offset.Zero,
                    alpha = 1f
                )
            }
            
            // 优化：只绘制当前正在书写的路径（使用平滑处理）
            if (currentPoints.isNotEmpty()) {
                val smoothedPath = smoothPath(currentPoints)
                drawPath(
                    path = smoothedPath,
                    color = PrimaryBlue,
                    style = Stroke(
                        width = if (currentPressure > 0) 2f + currentPressure * 4f else 4f, // 根据压力调整线宽
                        cap = StrokeCap.Round,
                        join = StrokeJoin.Round
                    )
                )
            }
            
            // 引用forceRedraw确保重绘
            if (forceRedraw > 0) {
                // 这个if语句只是为了引用forceRedraw变量，没有实际功能
            }
            }
            
            // 目标字符（浅色背景）- 移到Canvas之后，确保显示在顶层
            Text(
                text = character,
                fontSize = 80.sp,
                fontWeight = FontWeight.Bold,
                color = PrimaryBlue.copy(alpha = 0.2f),
                textAlign = TextAlign.Center,
                modifier = Modifier.align(Alignment.Center)
            )
            
            // 清除按钮
            Button(
                onClick = {
                    path = Path()
                    currentPath = Path()
                    allPaths = emptyList()
                    showResult = false
                    score = 0f
                    currentPressure = 0f
                    strokeCount = 0
                    hasCompletedStrokes = false
                    currentPoints = emptyList() // 清空路径点
                    cachedBitmap = null // 清空缓存
                    cacheDirty = true // 标记缓存需要更新
                },
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .size(24.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = ButtonRed,
                    contentColor = TextWhite
                ),
                shape = RoundedCornerShape(4.dp)
            ) {
                Text(
                    text = "×",
                    fontSize = 12.sp
                )
            }
            
            // 笔画进度提示
            if (!hasCompletedStrokes && strokeCount > 0) {
                Text(
                    text = "$strokeCount/$estimatedStrokes",
                    fontSize = 12.sp,
                    color = PrimaryBlue,
                    modifier = Modifier
                        .align(Alignment.TopStart)
                        .background(Color.White.copy(alpha = 0.7f))
                        .padding(4.dp)
                )
            }
            
            // 评分结果
            if (showResult) {
                Box(
                    modifier = Modifier
                        .align(Alignment.BottomCenter)
                        .fillMaxWidth()
                        .background(Color.White.copy(alpha = 0.8f))
                        .padding(4.dp)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "${score.toInt()}分",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold,
                            color = when {
                                score >= 90 -> ButtonGreen
                                score >= 70 -> ButtonBlue
                                else -> ButtonRed
                            }
                        )
                        
                        Button(
                            onClick = {
                                path = Path()
                                currentPath = Path()
                                allPaths = emptyList()
                                showResult = false
                                score = 0f
                                currentPressure = 0f
                                strokeCount = 0
                                hasCompletedStrokes = false
                                currentPoints = emptyList() // 清空路径点
                                cachedBitmap = null // 清空缓存
                                cacheDirty = true // 标记缓存需要更新
                            },
                            modifier = Modifier.size(40.dp, 20.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = ButtonBlue,
                                contentColor = TextWhite
                            ),
                            shape = RoundedCornerShape(4.dp)
                        ) {
                            Text(
                                text = "重写",
                                fontSize = 10.sp
                            )
                        }
                    }
                }
            }
        }
    }
}
                    @Composable
fun WritingCardDemo(
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val characterList = listOf("1", "A", "一", "人", "大", "小")
    
    var currentCharacterIndex by remember { mutableStateOf(0) }
    
    Surface(
        modifier = modifier.fillMaxSize(),
        color = MaterialTheme.colorScheme.background
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 标题栏
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Button(
                    onClick = onBackClick,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = ButtonBlue,
                        contentColor = TextWhite
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text(
                        text = "返回",
                        fontSize = 16.sp
                    )
                }
                
                Spacer(modifier = Modifier.weight(1f))
                
                Text(
                    text = "书写卡片测试",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = TextPrimary
                )
                
                Spacer(modifier = Modifier.weight(1f))
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 说明文本
            Text(
                text = "使用压感笔在浅色字符上描摹",
                fontSize = 16.sp,
                color = TextPrimary,
                textAlign = TextAlign.Center
            )
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 小型书写卡片
            MiniWritingCard(
                character = characterList[currentCharacterIndex],
                onWritingComplete = { score ->
                    // 处理书写完成
                }
            )
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 字符切换按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Button(
                    onClick = {
                        if (currentCharacterIndex > 0) {
                            currentCharacterIndex--
                        }
                    },
                    enabled = currentCharacterIndex > 0,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (currentCharacterIndex > 0) ButtonBlue else ButtonBlue.copy(alpha = 0.5f),
                        contentColor = TextWhite
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text(
                        text = "上一个",
                        fontSize = 16.sp
                    )
                }
                
                Button(
                    onClick = {
                        if (currentCharacterIndex < characterList.size - 1) {
                            currentCharacterIndex++
                        }
                    },
                    enabled = currentCharacterIndex < characterList.size - 1,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (currentCharacterIndex < characterList.size - 1) ButtonBlue else ButtonBlue.copy(alpha = 0.5f),
                        contentColor = TextWhite
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text(
                        text = "下一个",
                        fontSize = 16.sp
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 压感笔使用提示
            Text(
                text = "提示：使用三星压感笔可以获得更好的书写体验",
                fontSize = 14.sp,
                color = TextPrimary.copy(alpha = 0.7f),
                textAlign = TextAlign.Center
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun MiniWritingCardPreview() {
    MaterialTheme {
        MiniWritingCard(
            character = "1",
            onWritingComplete = {}
        )
    }
}

@Preview(showBackground = true, heightDp = 800)
@Composable
fun WritingCardDemoPreview() {
    MaterialTheme {
        WritingCardDemo(
            onBackClick = {}
        )
    }
}